import request from "@/router/axios";
import store from '@/store'

// 企业微信id
const agentObj = {
    "customerDetail": 1000014,//客户详情
    "verbalManage": 1000015,//话术管理
    "financialShop": 1000016,//产品管理
    "marketMaterial": 1000017,//营销素材
    "financialReminder": 1000018,//金融提醒 
    "customerQRcode": 1000027,//一客一码
    "managerReminder": 1000011,//经理提醒
}

// 金融提醒对应的事件名
export const eventTypeObj = {
    "customerDetail": "todo",//客户详情-待办事项提醒
    "marketMaterial": "marketing",//开启了行为追踪的营销素材
}

/**
 * 判断是否为空
 */
const validatenull = function (val) {
    if (typeof val === 'boolean') {
        return false
    }
    if (typeof val === 'number') {
        return false
    }
    if (val instanceof Array) {
        if (val.length === 0) return true
    } else if (val instanceof Object) {
        if (JSON.stringify(val) === '{}') return true
    } else {
        if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') return true
        return false
    }
    return false
}

/**
 * 存储localStorage
 */
export const setSession = (params = {}) => {
    let {
        name,
        content,
        type
    } = params;
    name = 'madp' + name;
    const obj = {
        dataType: typeof (content),
        content: content,
        type: type,
        datetime: new Date().getTime()
    };
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj))
    else window.localStorage.setItem(name, JSON.stringify(obj))
}

/**
 * 获取localStorage
 */

export const getSession = (params = {}) => {
    let {
        name,
        debug
    } = params;
    name = 'madp' + name;
    let obj = {}
    let content
    obj = window.sessionStorage.getItem(name)
    if (validatenull(obj)) obj = window.localStorage.getItem(name)
    if (validatenull(obj)) return
    try {
        obj = JSON.parse(obj)
    } catch (e) {
        return obj
    }
    if (debug) {
        return obj
    }
    if (obj.dataType === 'string') {
        content = obj.content
    } else if (obj.dataType === 'number') {
        content = Number(obj.content)
    } else if (obj.dataType === 'boolean') {
        content = eval(obj.content)
    } else if (obj.dataType === 'object') {
        content = obj.content
    }
    return content
}


// 金融提醒需要用到
export const apiUrl = document.location.origin;

//获取当前页面url
export const getPageUrl = () => {
    let urls = window.location.href;
    return urls;
}
// 获取页面参数
export const getSearchString = (key, url) => {
    var str = url;
    var arr = [];
    if (str.split("?")[1]) {
        arr = str.split("?")[1].split("&");
    }
    var obj = {};
    // 将每一个数组元素以=分隔并赋给obj对象
    for (var i = 0; i < arr.length; i++) {
        var tmp_arr = arr[i].split("=");
        obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
    }
    return obj[key];
}

// 页面路径中拼接参数
export const joinSearchString = (obj, url) => {
    url = url ? url : getPageUrl()
    let urlArr = url.split('#/')
    let str = urlArr[0]
    for (let key in obj) {
        if (!obj[key]) continue
        if (str.includes('?')) {
            str += `&${key}=${obj[key]}`
        } else {
            str += `?${key}=${obj[key]}`
        }
    }
    return urlArr[1] ? `${str}#/${urlArr[1]}` : str
}

/**
 * 获取当前页面分享路径
 * @param {*} route 路由
 * @param {*} params 参数
 * @returns 
 */
export const getShareUrl = (route, params = {}) => {
    let info = getPageUrl().split('#/')[1].split('?')
    route = route || info[0];    // 获取路由
    let queryArr = info[1] ? info[1].split('&') : [];
    let query = {}
    queryArr.forEach(ele => {
        if (ele) {
            let a = ele.split('=')[0]
            let b = ele.split('=')[1]
            query[a] = b
        }
    })
    query = Object.assign(query, params, { isSharePage: 1, wxUserId: store.state.vuex_wxUserId, wxExternalUserid: store.state.vuex_wxExternalUserid, chatId: store.state.vuex_chatId })
    let str = ''
    for (let key in query) {
        if (!query[key]) continue
        let value = query[key]
        if (!/.*[u4e00-u9fa5]+.*$/.test(value)) {    // 判断当前参数中是否有中文
            value = encodeURIComponent(value)
        }
        if (!str) {
            str += `${key}=${value}`
        } else {
            str += `&${key}=${value}`
        }
    }
    return `${apiUrl}/#/${route}?${str}`

}

/**
 * 获取当前企业微信用户信息userid相关的业务代码
 * @param {*} obj object{appId}
 * @param {*} callback 获取userid后的处理
 */
export const getWxUserId = (appId, callback) => {
    let searchUrl = location.search; //当前页面地址
    let codeStr = getSearchString("code", searchUrl);
    if (!codeStr) {
        let a = document.createElement("a");
        let currentUrl = encodeURIComponent(
            window.location.href
        );
        let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${currentUrl}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
        a.href = url;
        a.click();
    } else {
        getCurrentEmployeeInfo(codeStr, data => {
            callback && callback(data);
            // 获取到用户信息后重置url
            let urlArr = getPageUrl().split('#/')
            let url = urlArr[0]
            let cid = getSearchString('cid', url)
            let tid = getSearchString('tid', url)
            let aid = getSearchString('aid', url)
            history.replaceState(null, '', `/?cid=${cid}&tid=${tid}&aid=${aid}#/${urlArr[1]}`)
        });

    }
}

// 获取当前企业微信用户信息userid(成员id)-中台接口
export const getCurrentEmployeeInfo = (codeStr, callback) => {
    let url = getPageUrl().split("#/")[0];
    let agentId = getSearchString("aid", url) + '';
    request({
        url: `/cp/employee-info/info?agentId=${agentId}&code=${codeStr}`,
        method: "get"
    }).then(res => {
        res = res.data;
        if (res.code === 0 && res.data) {
            callback && callback(res.data);
        }
    })

}

// 判断是否是微信浏览器且区分pc端和app
export const isPcWeixin = () => {
    let sUserAgent = navigator.userAgent.toLowerCase()
    let bIsIpad = sUserAgent.match(/ipad/i) == 'ipad'
    let bIsIphoneOs = sUserAgent.match(/iphone os/i) == 'iphone os'
    let bIsMidp = sUserAgent.match(/midp/i) == 'midp'
    let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == 'rv:1.2.3.4'
    let bIsUc = sUserAgent.match(/ucweb/i) == 'ucweb'
    let bIsAndroid = sUserAgent.match(/android/i) == 'android'
    let bIsCE = sUserAgent.match(/windows ce/i) == 'windows ce'
    let bIsWM = sUserAgent.match(/windows mobile/i) == 'windows mobile'

    if (sUserAgent.match(/MicroMessenger/i) == 'micromessenger') {
        if (
            bIsIpad ||
            bIsIphoneOs ||
            bIsMidp ||
            bIsUc7 ||
            bIsUc ||
            bIsAndroid ||
            bIsCE ||
            bIsWM
        ) {
            return false
        } else {
            return true
        }
    } else {
        return false
    }
}
export const generParamsStr = (obj) => {
    let rangeArr = ''
    let param = ''
    if (obj && typeof obj === 'object') {
        for (let i in obj) {
            if (rangeArr === '') {
                rangeArr += '?'
            }
            if (Object.prototype.hasOwnProperty.call(obj, i) && obj[i] !== '') {
                rangeArr += `${i}=${obj[i]}&`
            }
        }
        return rangeArr.replace(/&$/, '')
    }
    return param
}
export const generParamObj = () => {
    let arr = decodeURI(window.location.href).split('?')
    let rst = {}
    if (arr && arr.length > 1) {
        let paramStr = arr[1]
        let params = paramStr.split('&')

        for (let item of params) {
            let keyAndVal = item.split('=')
            rst[keyAndVal[0]] = keyAndVal[1]
        }
    }
    return rst
}


// 判断当前环境
export const pageEnv = () => {
    var isMobile = window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i); // 是否手机端
    var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
    var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
    if (isComWx && isMobile) { //手机端企业微信
        return 'com-wx-mobile'
    } else if (isComWx && !isMobile) { //PC端企业微信
        return 'com-wx-pc'
    } else if (isWx && isMobile) { // 手机端微信
        return 'wx-mobile';
    } else if (isWx && !isMobile) { // PC端微信
        return 'wx-pc';
    } else {
        return 'other';
    }
}
// 是否在企业微信环境
export const isComWx = () => {
    var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
    return !!isComWx
}
// 是否在微信环境(并且不在企业微信中)
export const isWx = () => {
    var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
    var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
    return !isComWx && isWx
}
// 是否移动端
export const isMobile = () => {
    var isMobile = window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i); // 是否手机端
    return !!isMobile
}
// 是否Android
export const isAndroid = () => {
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
    return !!isAndroid
}
// 是否IOS
export const isIOS = () => {
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    return !!isIOS
}
// 判断是否微信环境
// 判断手机系统
export const mobileSys = () => {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器 
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isAndroid) {
        return 'android'
    } else if (isIOS) {
        return 'ios'
    } else {
        return ''
    }
}